package com.metel.mservice.common.jaxrs.provider;

import java.io.IOException;
import java.io.OutputStream;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;

import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;

import org.apache.cxf.jaxrs.provider.BinaryDataProvider;

import com.metel.mservice.common.jaxrs.ImageDataInputStream;

/**
 * ImageDataProvider
 * 
 * @author sr80.choi
 */
public class ImageDataProvider extends BinaryDataProvider {

	@Override
	public void writeTo(Object o, Class<?> clazz, Type genericType, Annotation[] annotations, MediaType type,
			MultivaluedMap<String, Object> headers, OutputStream os) throws IOException {
		// set image content-type
		MediaType realType = findMediaType(o, type);
		setImageContentType(headers, realType);

		super.writeTo(o, clazz, genericType, annotations, realType, headers, os);

	}

	private MediaType findMediaType(Object o, MediaType oldType) {
		MediaType newType = null;
		if (o instanceof ImageDataInputStream) {
			String contentType = ((ImageDataInputStream) o).getContentType();

			try {
				newType = new MediaType(contentType.substring(0, contentType.indexOf("/")),
						contentType.substring(contentType.indexOf("/") + 1));
			} catch (Exception e) {
				newType = null;
			}
		}

		if (newType == null) {
			newType = oldType;
		}

		return newType;
	}

	private void setImageContentType(MultivaluedMap<String, Object> headers, MediaType realType) {
		// headers.add(HttpHeaders.CONTENT_TYPE, realType);
		headers.putSingle(HttpHeaders.CONTENT_TYPE, realType);
	}
}
